/* use -lpopt to link on a linux box */
#include <popt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>             /* for strerror() */
#include <unistd.h>

void usage(int exitcode, char *error, char *addl) {
   if (error) fprintf(stderr, "%s: %s\n", error, addl);
   fprintf(stderr, "Usage: expopt [options] \n"
                   " [options] include:\n"
                   "    --help (-h) for this help\n"
                   "    --iarg=int (-i int)\n"
                   "    --carg=string (-c string)\n");
   exit(exitcode);
}

int main(int argc, char *argv[]) {
   int  iarg = 0;     /* used in argument parsing to set speed */
   char c, *carg = NULL;
   poptContext optCon;   /* context for parsing command-line options */
   struct poptOption optionsTable[] = {
	    { "iarg", 'i', POPT_ARG_INT, &iarg, 0 },
	    { "carg", 'c', POPT_ARG_STRING, &carg, 'c' },
	    { "help", 'h', 0, 0, 'h' },
	    { NULL, 0, 0, NULL, 0 }
   };

   if (argc < 2) usage(1, "Not enough arguments", "");

   optCon = poptGetContext("expopt", argc, argv, optionsTable, 0);

   /* option processing will now modify pts and sts */
   while ((c = poptGetNextOpt(optCon)) >= 0) {
      printf("handling arg %c\n",c);
      switch (c) {
         case 'h':
            printf("got help request\n");
            usage(0, NULL, NULL);
            break;
         case 'i': 
	    // note this will not be done since last value in
	    // options table for iarg is 0 
            printf("got iarg=%d\n",iarg);
            break;
         case 'c': 
            printf("got carg=%s\n",carg);
            break;
      }
   }

   if (c < -1) {
      /* an error occurred during option processing */
      fprintf(stderr, "%s: %s\n", 
              poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
              poptStrerror(c));
      return 1;
   }
   printf("iarg=%d\n",iarg);
   if (carg)
       printf("carg=%s\n",carg);

   exit(0);
}
